package org.linloong.modules.apis.ai.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.core.result.Result;
import org.linloong.modules.apis.ai.dto.ChatRequest;
import org.linloong.modules.apis.ai.dto.ChatResponse;
import org.linloong.modules.apis.ai.dto.FileUploadRequest;
import org.linloong.modules.apis.ai.dto.FileUploadResponse;
import org.linloong.modules.apis.ai.service.DifyService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import jakarta.validation.Valid;

/**
 * AI 聊天控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
@Tag(name = "AI聊天", description = "AI聊天相关接口")
public class ChatController {
    
    private final DifyService difyService;
    
    @PostMapping("/message")
    @Operation(summary = "发送聊天消息", description = "向AI发送消息并获取回复")
    public Result<ChatResponse> sendMessage(@Valid @RequestBody ChatRequest request) {
        log.info("收到聊天请求: {}", request.getMessage());
        try {
            ChatResponse response = difyService.chatSync(request);
            if (response.getSuccess()) {
                log.info("聊天响应成功，消息ID: {}", response.getMessageId());
                return Result.success(response);
            } else {
                log.error("聊天响应失败: {}", response.getError());
                return Result.fail(response.getError());
            }
        } catch (Exception e) {
            log.error("聊天请求处理异常", e);
            return Result.fail("聊天服务暂时不可用，请稍后重试");
        }
    }


    @PostMapping(value = "/message/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "Flux流式发送聊天消息", description = "使用Flux流式向AI发送消息")
    public Flux<String> sendMessageFlux(@RequestBody ChatRequest request) {
        log.info("收到Flux流式聊天请求: {}", request.getMessage());
        return difyService.chatStream(request);

    }

    @GetMapping(value = "/echart/get")
    @Operation(summary = "获取echarts数据", description = "根据对话ID获取echarts数据")
    public Result<String> getEchartData(@RequestParam(required = true) String converstionId) throws JsonProcessingException {
        return difyService.getEchartData(converstionId);

    }
    
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查聊天服务是否正常")
    public Result<String> health() {
        return Result.success("聊天服务运行正常");
    }

    // 实体类方式
    @PostMapping("/files/upload")
    @Operation(summary = "上传文件(实体类)", description = "使用实体类上传文件到第三方服务")
    public Result<FileUploadResponse> uploadFileEntity(@ModelAttribute FileUploadRequest request) {
        try {
            FileUploadResponse response = difyService.uploadFile(request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }
}